import moment from 'moment'


// pages/goodsInfo/goodsInfo.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsInfo:{},
        goodsPicture:{},
        imgList:[],
        isCollect:false,
        openid:'',
        orderId:'',
        loading:0,
        goodsId:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      
        const openid = wx.getStorageSync('openid')
       
        this.setData({
            openid,
            goodsId:options.id
        })
        // console.log(options)
        this.getGoodsInfo(options.id)
    },
    updatePublish(){
        wx.navigateTo({
            url:'/pages/publishDetail/publishDetail?goodsId='+this.data.goodsInfo.goodsId,
        });
    },
    deletePublish(){
        const goodsId = this.data.goodsInfo.goodsId
        console.log('delete')
        wx.showModal({
           
            content: '确定删除？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: 'grey',
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
                if (result.confirm) {
                    wx.request({
                        url:'http://127.0.0.1:6060/api/deleteGoods',
                        data:{
                           goodsId
                        },
                        method:'get',
                        
                        success:(res) =>{
                            // console.log(res)
                            wx.switchTab({
                                url:'/pages/index/index',
                            });
                            setTimeout(() => {
                              
                              wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 1500
                              })
                            }, 100);
                              
                          
                        }
                    })
                }
            },
            fail: () => {},
            complete: () => {}
        });
    },
    handleCollect(){
       let isCollect = !(this.data.isCollect)
       this.setData({
           isCollect
       })
       if(this.data.isCollect){
           const collectList = wx.getStorageSync('collectList')||[];
             collectList.push(this.data.goodsInfo)
           wx.setStorageSync('collectList', collectList);
       }else{
        const collectList = wx.getStorageSync('collectList');
        const filCollectList = collectList.filter((v)=>{
            return v.goodsId != this.data.goodsInfo.goodsId
        })
        console.log(filCollectList)
        wx.setStorageSync('collectList',filCollectList);
       }
    },
    login(e){
       
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res.userInfo)
              this.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              })
              wx.login({
                //获取code
               
                success:  (res)=> {
                  var code = res.code; //返回code
                  const userInfo = this.data.userInfo
                  wx.setStorageSync("userInfo",userInfo);
                  wx.request({
                      url: 'http://127.0.0.1:6060/api/addUserInfo',
                      data: {
                          code,
                          userInfo
                        
                      },
                      header: {'content-type':'application/json'},
                      method: 'post',
                     
                      success: (result) => {
                          console.log(result.data.message)
                          this.setData({
                              openid:result.data.message
                          })
                          wx.setStorageSync("openid",result.data.message);
                      },
                     
                  });
                    
                }
            })
              wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                 
                  duration: 1500,
                  mask: true,
                 
              });
                
           
            }
          })
        },
    // 预订商品点击事件
    orderGoods(){
      
        if(!this.data.openid){
           this.login()
           return
        }
        wx.request({
            url: 'http://127.0.0.1:6060/api/getGoodsInfo',
            data: {
                id:this.data.goodsId
            },
            header: {'content-type':'application/json'},
            method: 'GET',
            dataType: 'json',
            responseType: 'text',
            success: (result) => {
            
              
               if(result.data.message[0].state !== '等待预订'){
                   wx.showToast({
                       title:'该商品已被预订了',
                       icon:'none'
                       
                   })
                   return 
               }else{
                wx.request({
                    url: 'http://127.0.0.1:6060/api/addOrder',
                    data: {
                       goodsId:this.data.goodsInfo.goodsId,
                       userId:this.data.goodsInfo.userId,
                       time:moment().format('YY-MM-DD HH:mm:ss'),
                       buyUserId:this.data.openid,
                       type:"闲置物品"
                    },
                    header: {'content-type':'application/json'},
                    method: 'post',
                    dataType: 'json',
                    responseType: 'text',
                    success: (result) => {
                       
                        console.log(result.data)
                        this.setData({
                            orderId:result.data.message
                        })
                        wx.navigateTo({
                            url: '/pages/orderSuccess/orderSuccess?phone='+this.data.goodsInfo.phone+'&orderId='+this.data.orderId,
                          })
                    },
                    fail:()=>{
                          wx.showToast({
                                title: '预订失败',
                                icon: 'error',
                                
                                duration: 1500,
                                mask: false,
                            
                            });
                    }
                   
                });
               }
            },
           
        });
        // wx.request({
        //     url: 'http://127.0.0.1:6060/api/addOrder',
        //     data: {
        //        goodsId:this.data.goodsInfo.goodsId,
        //        userId:this.data.goodsInfo.userId,
        //        time:moment().format('YY-MM-DD HH:mm:ss'),
        //        buyUserId:this.data.openid,
               
        //     },
        //     header: {'content-type':'application/json'},
        //     method: 'post',
        //     dataType: 'json',
        //     responseType: 'text',
        //     success: (result) => {
               
        //         console.log(result.data)
        //         this.setData({
        //             orderId:result.data.message
        //         })
        //         wx.navigateTo({
        //             url: '/pages/orderSuccess/orderSuccess?phone='+this.data.goodsInfo.phone+'&orderId='+this.data.orderId,
        //           })
        //     },
           
        // });
    },
    getGoodsInfo(id){
        wx.showLoading({
            title: '正在加载',
            mask:true
          });
        wx.request({
            url: 'http://127.0.0.1:6060/api/getGoodsInfo',
            data: {
                id:id
            },
            header: {'content-type':'application/json'},
            method: 'GET',
            dataType: 'json',
            responseType: 'text',
            success: (result) => {
                // console.log(result.data.message)
               this.setData({
                   goodsInfo:result.data.message[0]
               })
            },
           
        });
        wx.request({
            url: 'http://127.0.0.1:6060/api/getGoodsPicture',
            data: {
                id:id
            },
            header: {'content-type':'application/json'},
            method: 'GET',
            dataType: 'json',
            responseType: 'text',
            success: (result) => {
                wx.hideLoading()
                wx.showToast({
                  title: '加载成功',
                  icon: 'success',
                  duration:500
                })
            // console.log(result.data.message)
            const imgList = []
            const goodsPicture = result.data.message[0]
            for(let i in goodsPicture){
                imgList.push(goodsPicture[i])
            }
            imgList.splice(0,1)//删除第一项
            const imgListNew = imgList.filter(v=>{
                return (v!='')
            })
            this.setData({
                loading:1,
               goodsPicture,
               imgList:imgListNew
            })
            },
           
        });
          
    },

    previewImage(e){
        wx.previewImage({
            current:e.currentTarget.dataset.src,
            urls:this.data.imgList
        })
    }

//    getA(){
//        const imgList = []
//        const goodsPicture = this.data.goodsPicture
//        for(let i in goodsPicture){
//            imgList.push(goodsPicture[i])
//        }
//        console.log(imgList)
//        this.setData({
//            imgList
//        })
//     console.log('ee')
//    }
    
    
})